'use strict';
/**
 * 七牛上传插件
 * created by andy
 * 
 *  qiniu(submitData)  //data 需要上传的数据 值 可包含wx.chooseImage 接口返回 本地图片
                    .then(function (submitData) { 返回submitData 并且以替换成上传后的图片路径
                        console.log("submitData", submitData)
                    })
                    .catch((err) => {
                        console.warn("qiniu upload error", err)
                    });
*/

var lmfConfig = require('../config.js');
var Promise = require('../utils/es6-promise.min.js');
var api = require('./lmfService.js');
var qiniuTool = require('../utils/qiniu.js');

var qiniuConfig = {
  qiniuDomain: '',
  qiniuUploadURL: 'https://upload.qiniup.com',
  qiniuImageURLPrefix: lmfConfig.alias,
  qiniuUploadTokenURL: "/qiniu/getToken",
  qiniuUploadToken: ''
}

var right2word = (s) => {
  if (!isNaN(s)) {
    s += "";
  }
  return ('0' + s).substr(s.length - 1);
}
var getQiniuToken = () => {
  return Promise.resolve(qiniuConfig.qiniuDomain && qiniuConfig.qiniuUploadToken)
    .then((hasToken) => {
      if (hasToken) {
        return true;
      }
      return api.post(qiniuConfig.qiniuUploadTokenURL, {})
        .then((data) => {
          qiniuConfig.qiniuDomain = data.domain;
          qiniuConfig.qiniuUploadToken = data.token;
          return true
        })
    })
}
function doUpload(filePath) {

  return new Promise((resolve, reject) => {
    //排除非本地图片
    if (!(filePath.indexOf('wxfile://tmp_') === 0 || filePath.indexOf('http://tmp/') === 0)) {
      resolve({ origin_path: filePath, new_path: filePath });
      return;
    }
    //文件路径
    var path = ((prefix) => {
      var now = new Date();
      return prefix + '/' + now.getFullYear() + "/" + right2word(now.getMonth() + 1) + '/' + right2word(now.getDate()) + '/'
    })(qiniuConfig.qiniuImageURLPrefix);
    //七牛需要数据
    var formData = {
      'token': qiniuConfig.qiniuUploadToken,
      'key': path + (filePath.indexOf('wxfile://tmp_') === 0 && filePath.split('//tmp_')[1] || filePath.split('//tmp/')[1])
    };
    wx.uploadFile({
      url: qiniuConfig.qiniuUploadURL,
      filePath: filePath,
      name: 'file',
      formData: formData,
      success: (res) => {
        if (res.statusCode == 200) {
          resolve({ origin_path: filePath, new_path: qiniuConfig.qiniuDomain + '/' + JSON.parse(res.data).key });
        } else {
          console.error("uploadFile error", res);
          reject("")
        }
      },
      fail: (error) => {
        console.error('七牛上传出错', error);
        reject("");
      }
    })
  })
}


var uploadImages = (filePathes) => {
  if (!filePathes) {
    return Promise.resolve([]);
  }

  if (filePathes.length == 0) {
    return Promise.resolve([]);
  }
  return getQiniuToken().then(() => {
    return new Promise((resolve, reject) => {
      var _filePath = ['', '', ''].slice(0, filePathes.length);
      filePathes.forEach((filePath) => {

        doUpload(filePath).then((realPath) => {
          filePathes.forEach(function (__filePath, __index) {
            if (__filePath == realPath.origin_path) {
              _filePath[__index] = realPath.new_path
            }
          })
          var isAllSuccessFiles = _filePath.every(function (__filePath) {

            return __filePath != ""
          })
          if (isAllSuccessFiles) {
            resolve(_filePath);
          }
        }).catch(() => {
          _filePath.push("");
          if (_filePath.length == filePathes.length) {
            resolve(_filePath);
          }
        })
      })
    });

  })

};

module.exports = (submitData) => {
  var fileBase64s = qiniuTool.getImages(submitData);
  if (fileBase64s.length == 0) {
    return Promise.resolve(submitData);
  }
  return uploadImages(fileBase64s)
    .then(function (successData) {
       qiniuTool.assignData(submitData, successData)
      return submitData
    })

};